package com.wuh.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.wuh.model.CastleAtta;
import com.wuh.model.CastleCollect;
import com.wuh.model.CastleComment;
import com.wuh.model.CastleInfo;
import com.wuh.model.CastleSignup;
import com.wuh.model.CastleType;
import com.wuh.model.GroupInfo;
import com.wuh.model.GroupUser;
import com.wuh.model.MallType;
import com.wuh.model.Teacher;
import com.wuh.model.TeacherPhrase;
import com.wuh.model.User;
import com.wuh.service.CastleService;
import com.wuh.service.GroupService;
import com.wuh.service.TeacherService;

@Controller
public class CastleController {

	@Autowired
	private CastleService castleService;
	
	@Autowired
	private TeacherService teacherService;

	@Autowired
	private GroupService groupService;
	
	 // 管理员功能实现	
	/**
	 * 跳转到福利城堡管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/toAdminCastle")
	public String toAdminCastle(CastleInfo castleInfo, Model model) {
		PageInfo<CastleInfo> pageInfo = castleService.getCastleInfos(castleInfo);
		List<CastleType> castleTypes = castleService.getCastleTypes();
		List<MallType> mallTypes = castleService.getMallTypes();
		List<Teacher> teachers = teacherService.getTeachers();
		model.addAttribute("teachers", teachers);
		model.addAttribute("castleTypes", castleTypes);
		model.addAttribute("mallTypes", mallTypes);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("castleInfo", castleInfo);	
		return "welfareCastle/admin_castle";
	}
	
	/**
	 * 关闭课程
	 * @return
	 */
	@RequestMapping("/closeCastles")
	public String closeCastles(Integer[] ids) {
		castleService.closeCastles(ids);
		return "redirect:/toAdminCastle";
	}
	
	/**
	 * 恢复课程
	 * @return
	 */
	@RequestMapping("/refreshCastles")
	public String refreshCastles(Integer[] ids) {
		castleService.refreshCastles(ids);
		return "redirect:/toAdminCastle";
	}
	
	/**
	 * 删除课程
	 * @return
	 */
	@RequestMapping("/delCastles")
	public String delCastles(Integer[] ids) {
		castleService.delCastles(ids);
		return "redirect:/toAdminCastle";
	}


	 //用户功能实现	
	/**
	 * 跳转到我的福利城堡页面
	 * 
	 * @return
	 */
	@RequestMapping("/toMyCastle")
	public String toMyCastle(CastleInfo castleInfo, Model model, HttpSession session) {
		String loginMessage = (String) session.getAttribute("loginMessage");
		if (loginMessage == "teacher") { //老师登录的时候
			Teacher teacher = (Teacher) session.getAttribute("sess_user");			
			castleInfo.setTeacher_id(teacher.getTeacher_id());
			castleInfo.setIsWhich(1);
			PageInfo<CastleInfo> pageInfo = castleService.getCastleInfos(castleInfo);
			model.addAttribute("pageInfo", pageInfo);
		} else if (loginMessage == "user") { //用户登录的时候
			User user = (User) session.getAttribute("sess_user");
			CastleSignup castleSignup = new CastleSignup();		
			if(castleInfo.getMall_type() == null) {
				castleInfo.setMall_type(1);
			}
			castleSignup.setCastleInfo(castleInfo);
			castleSignup.setUser_id(user.getUser_id());
			PageInfo<CastleSignup> pageInfo = castleService.getSignups(castleSignup);
			model.addAttribute("pageInfo", pageInfo);
			List<TeacherPhrase> teacherPhrases = castleService.getTeacherPhraseByUserId(user.getUser_id());
			model.addAttribute("teacherPhrases", teacherPhrases);
		}
		
		model.addAttribute("castleInfo", castleInfo);
		return "person/user_myCastle";
	}

	/**
	 * 跳转到发布福利城堡页面
	 * 
	 * @return
	 */
	@RequestMapping("/toCastlePublish")
	public String toCastlePublish(Integer castle_id, Model model, HttpSession session) {
		List<CastleType> castleTypes = castleService.getCastleTypes();
		List<MallType> mallTypes = castleService.getMallTypes();
		CastleInfo castle = new CastleInfo();
		List<CastleAtta> castleAttas = null;
		if (castle_id != null) {// 配置跳转到修改操作的相关信息
			castle = castleService.getCastleInfoById(castle_id);
			castleAttas = castleService.getAttas(castle_id);
			castle.setSort(4);
		} else {// 配置跳转到发布页面的信息
			castle.setCastle_cycle("");
			castle.setSort(3);
		}
		Teacher teacher = (Teacher) session.getAttribute("sess_user");
		GroupInfo groupInfo = new GroupInfo();
		groupInfo.setTeacher(teacher);
		List<GroupInfo> groups = groupService.getGroups1(groupInfo);
		model.addAttribute("groups", groups);
		model.addAttribute("castleAttas", castleAttas);
		model.addAttribute("castle", castle);
		model.addAttribute("castleTypes", castleTypes);
		model.addAttribute("mallTypes", mallTypes);
		return "welfareCastle/castle_publish";
	}

	/**
	 * 跳转到福利城堡页面里
	 * 
	 * @return
	 */
	@RequestMapping("/toCastle")
	public String toCastle(CastleInfo castleInfo, Model model, HttpSession session) {
		if (castleInfo.getMall_type() == null) {
			castleInfo.setMall_type(1);
		} 
		castleInfo.setIsWhich(1); //判断是不是前台，前台的话，不显示status为2的数据
		PageInfo<CastleInfo> pageInfo = castleService.getCastleInfos(castleInfo);
		List<CastleType> castleTypes = castleService.getCastleTypes();
		List<MallType> mallTypes = castleService.getMallTypes();
		if(session.getAttribute("sess_user") != null && session.getAttribute("loginMessage").equals("user")) {
			User user = (User) session.getAttribute("sess_user");
			List<TeacherPhrase> teacherPhrases = castleService.getTeacherPhraseByUserId(user.getUser_id());
			model.addAttribute("teacherPhrases", teacherPhrases);
		}		
		model.addAttribute("castleTypes", castleTypes);
		model.addAttribute("mallTypes", mallTypes);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("castleInfo", castleInfo);		
		return "welfareCastle/castle";
	}
	
	@RequestMapping("/isBuy")
	@ResponseBody
	public Boolean isBuy(Integer castle_id, HttpSession session) {
		CastleSignup castleSignup = new CastleSignup();
		castleSignup.setCastle_id(castle_id);
		User user = (User) session.getAttribute("sess_user");
		castleSignup.setUser_id(user.getUser_id());
		CastleSignup signup = castleService.getSignup(castleSignup);
		if(signup != null) {
			return true;
		}
		return false;
	}

	/**
	 * 添加或修改福利商城商品信息
	 * 
	 * @param castleInfo
	 * @param request
	 */
	@RequestMapping("/addOrEditCastle")
	public String addOrEditCastle(CastleInfo castleInfo) {
		if (!castleInfo.getMyJpg().getOriginalFilename().equals("")) {
			String newname = uploadFile(castleInfo.getMyJpg());
			if(castleInfo.getImg_url() != "" && castleInfo.getImg_url() !=  null && castleInfo.getSort() == 4) {
				delFile(castleInfo.getImg_url());
			}
			castleInfo.setImg_url("castleFile\\" + newname);		
		}
		if (castleInfo.getSort() == 3) { // 添加操作
			System.out.println(castleInfo);
			castleService.addCastle(castleInfo);
			teacherService.editTeacherCaslteNum(castleInfo.getTeacher_id());
		} else if (castleInfo.getSort() == 4) { //修改操作
			castleService.editCastle(castleInfo);
		}

		if (!castleInfo.getMyfile().getOriginalFilename().equals("")) {
			CastleAtta castleAtta = new CastleAtta();
			castleAtta.setCastle_id(castleInfo.getCastle_id());
			castleAtta.setAttachment_name(castleInfo.getMyfile().getOriginalFilename());
			castleAtta.setAttachment_size((float) castleInfo.getMyfile().getSize());
			String newfile = uploadFile(castleInfo.getMyfile());
			castleAtta.setAttachment_url("castleFile\\" + newfile);
			castleService.addAtta(castleAtta);
		}
		
		return "redirect:/toMyCastle";
	}

	/**
	 * 跳转到福利城堡里的详细信息里
	 * 
	 * @return
	 */
	@RequestMapping("/toCastleDetail")
	public String toCastleDetail(Integer castle_id, Integer flag, Model model, HttpSession session) {
		CastleInfo castle = castleService.getCastleInfoById(castle_id);
		List<MallType> mallTypes = castleService.getMallTypes();
		List<CastleAtta> castleAttas = castleService.getAttas(castle_id);
		List<CastleInfo> castleInfos = castleService.getCastleInfoLimit();
		List<CastleComment> castleComments = castleService.getCastleComments(castle_id);
		CastleCollect collect = null;
		if(session.getAttribute("loginMessage") != null && session.getAttribute("loginMessage").equals("user")) {
			User user = (User) session.getAttribute("sess_user");
			CastleCollect castleCollect = new CastleCollect();
			castleCollect.setCastle_id(castle_id);
			castleCollect.setCollect_user(user.getUser_id());
			collect = castleService.getCastleCollect(castleCollect);
			List<TeacherPhrase> teacherPhrases = castleService.getTeacherPhraseByUserId(user.getUser_id());
			model.addAttribute("teacherPhrases", teacherPhrases);
		}		
		
		model.addAttribute("flag", flag);
		model.addAttribute("collect", collect);
		model.addAttribute("castleComments", castleComments);
		model.addAttribute("castleInfos", castleInfos);
		model.addAttribute("castleAttas", castleAttas);
		model.addAttribute("mallTypes", mallTypes);
		model.addAttribute("castle", castle);
		return "welfareCastle/castle_detail";
	}

	/**
	 * 删除Castle
	 * @return
	 */
	@RequestMapping("/delCastle")
	public String delCastle(Integer castle_id) {
		castleService.delAttas(castle_id);
		CastleInfo castleInfo = castleService.getCastleInfoById(castle_id);
		castleService.delCastle(castle_id);
		delFile(castleInfo.getImg_url());
		List<CastleAtta> castleAttas = castleService.getAttas(castle_id);	
		for(CastleAtta castleAtta : castleAttas) {
			delFile(castleAtta.getAttachment_url());
		}
		return "redirect:/toMyCastle";
	}
	
	/**
	 * 获取下载文件
	 * @param castle_id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getAttas")
	public List<CastleAtta> getAttas(Integer castle_id) {

		return castleService.getAttas(castle_id);
	}
	
	/**
	 * 下载文件
	 */
	@RequestMapping("/downloadAtta")
	public void downloadAtta(Integer attachment_id, HttpServletResponse response) {
		CastleAtta castleAtta = castleService.getAttaById(attachment_id);
		downloadFile(castleAtta.getAttachment_url(), castleAtta.getAttachment_name(), response);
	}
	
	/**
	 * 用户退出课程
	 * @return
	 */
	@RequestMapping("/delSignup")
	public String delSignup(CastleSignup castleSignup, HttpSession session) {
		User user = (User) session.getAttribute("sess_user");
		castleSignup.setUser_id(user.getUser_id());
		castleService.delSignup(castleSignup);
		CastleInfo castle = castleService.getCastleInfoById(castleSignup.getCastle_id());
		castle.setSignup_num(castle.getSignup_num() - 1);
		castleService.editCastle(castle);
		return "redirect:/toMyCastle";
	}
	
	/**
	 * 跳转到支付步骤一
	 * 
	 * @return
	 */
	@RequestMapping("/toStepOne")
	public String toStepOne(String pay_name, String pay_tel, Integer castle_id, Model model) {
		CastleInfo castle = castleService.getCastleInfoById(castle_id);
		model.addAttribute("castle", castle);
		model.addAttribute("pay_name", pay_name);
		model.addAttribute("pay_tel", pay_tel);
		return "payment/step_one";
	}

	/**
	 * 跳转到支付步骤二
	 * 
	 * @return
	 */
	@RequestMapping("/toStepTwo")
	public String toStepTwo(String pay_name, String pay_tel, Integer castle_id, Model model) {
		CastleInfo castle = castleService.getCastleInfoById(castle_id);
		model.addAttribute("castle", castle);
		model.addAttribute("pay_name", pay_name);
		model.addAttribute("pay_tel", pay_tel);
		return "payment/step_two";
	}

	/**
	 * 跳转到支付步骤三
	 * 
	 * @return
	 */
	@RequestMapping("/toStepThree")
	public String toStepThree(CastleSignup castleSignup, Model model) {
		castleService.addSignup(castleSignup);
		CastleInfo castle = castleService.getCastleInfoById(castleSignup.getCastle_id());
		castle.setSignup_num(castle.getSignup_num() + 1);
		castleService.editCastle(castle);
		GroupUser groupUser = new GroupUser();
		groupUser.setAdmin_id(castleSignup.getUser_id());
		groupUser.setGroup_id(castle.getGroup_id());
		groupUser.setCreate_time(new Date());
		groupUser.setType("0");
		groupService.insertGroupUser(groupUser);
		model.addAttribute("castle", castle);		
		return "payment/step_three";
	}

	/**
	 * 添加和删除关注（点赞和取关）
	 * @param castle_id
	 * @param flag
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addOrDelCollect")
	public int addOrDelCollect(Integer castle_id, Integer flag, HttpSession session) {
		User user = (User) session.getAttribute("sess_user");
		CastleCollect castleCollect = new CastleCollect();
		castleCollect.setCastle_id(castle_id);
		castleCollect.setCollect_user(user.getUser_id());
		CastleInfo castleInfo = castleService.getCastleInfoById(castle_id);
		Integer nowNum = 0;
		if(flag == 1) { //添加
			castleService.addCollect(castleCollect);			
			nowNum = castleInfo.getCollect_num() + 1;
		}else if(flag == 2) { //删除	
			castleService.delCollect(castleCollect);
			nowNum = castleInfo.getCollect_num() - 1;
		}
		castleInfo.setCollect_num(nowNum);
		castleService.editCastle(castleInfo);
		return nowNum;
	}
	
	/**
	 * 点赞或取消点赞
	 * @param teacherPhrase
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addOrDelPhrase")
	public int addOrDelPhrase(Integer teacher_id, Integer flag, HttpSession session) {
		Integer nowNum = 0;
		User user = (User) session.getAttribute("sess_user");
		TeacherPhrase teacherPhrase = new TeacherPhrase();
		teacherPhrase.setUser_id(user.getUser_id());
		teacherPhrase.setTeacher_id(teacher_id);
		Teacher teacher = teacherService.getTeacherById(teacher_id);
		if(flag == 1) {
			castleService.addTeacherPhrase(teacherPhrase);
			nowNum = teacher.getPhrase_num() + 1;
		}else if(flag == 2) {
			castleService.delTeacherPhrase(teacherPhrase);
			nowNum = teacher.getPhrase_num() - 1;
		}
		teacher.setPhrase_num(nowNum);
		teacherService.editTeacher(teacher);
		return nowNum;
	}
	/**
	 * 发表评论
	 * @param castleComment
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("/addComment1")
	public String addComment1(CastleComment castleComment, Model model, HttpSession session) {
		castleService.addComment1(castleComment);
		CastleInfo castleInfo = castleService.getCastleInfoById(castleComment.getCastle_id());
		castleInfo.setComment_num(castleInfo.getComment_num() + 1);
		castleService.editCastle(castleInfo);
		return "redirect:/toCastleDetail?castle_id=" + castleComment.getCastle_id() + "&flag=" + 1;
	}
	
	/**
	 * 删除评论
	 * @param castle_id
	 * @param coment_id
	 * @return
	 */
	@RequestMapping("/delComment")
	public String delComment(Integer castle_id, Integer coment_id) {
		castleService.delComment(coment_id);
		CastleInfo castleInfo = castleService.getCastleInfoById(castle_id);
		castleInfo.setComment_num(castleInfo.getComment_num() - 1);
		castleService.editCastle(castleInfo);
		return "redirect:/toCastleDetail?castle_id=" + castle_id + "&flag=" + 1;
	}
	
	/**
	 * 修改评论
	 * @return
	 */
	@RequestMapping("/editComment")
	public String editComment(CastleComment castleComment) {
		castleService.editComment(castleComment);
		return "redirect:/toCastleDetail?castle_id=" + castleComment.getCastle_id() + "&flag=" + 1;
	}
	

	/**
	 * 上传文件
	 * @param myFile
	 * @param request
	 * @return
	 */
	public String uploadFile(MultipartFile myFile) {

		String filepath = new String("src/main/resources/" + "static/castleFile");
		File staticFile = new File(filepath);
		// 获取文件原始名称
		String filename = myFile.getOriginalFilename();
		int lastIndex = filename.lastIndexOf(".");
		// 获取文件后缀名
		String suffix = filename.substring(lastIndex);
		// 文件新名称
		Date now = new Date();
		String newName = now.getTime() + suffix;
		String uploadPath = staticFile.getAbsolutePath() + File.separator + newName;
		File targetFile = new File(uploadPath);
		System.out.println(uploadPath);
		try {
			myFile.transferTo(targetFile);
			System.out.println("文件上传成功！");
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		return newName;
	}

	/**
	 * 删除文件
	 * @param filename
	 */
	public void delFile(String filename) {
		String filepath = new String("src/main/resources/" + "static");
		File staticFile = new File(filepath);
		String delPath =staticFile.getAbsolutePath() + File.separator + filename;
		File file = new File(delPath);
		if(file.delete()) {
			System.out.println("删除成功！");
		}else {
			System.out.println("文件未找到！");
		}
	}

	/**
	 * 下载文件
	 * @param filename
	 * @param downname
	 * @param response
	 */
	public void downloadFile(String filename, String downname, HttpServletResponse response) {
		String filepath = new String("src/main/resources/" + "static");
		File staticFile = new File(filepath);
		FileInputStream in = null;
		ServletOutputStream out = null;
		try {
			// 设置下载文件使用的报头
			response.setHeader("Content-Type", "application/x-msdownload");
			response.setHeader("Content-Disposition",
					"attachment; filename=" + new String(downname.getBytes("UTF-8"), "ISO8859-1"));
			// 读入文件
			in = new FileInputStream(staticFile.getAbsolutePath() +  File.separator + filename);
			// 得到响应对象的输出流，用于向客户端输出二进制数据
			out = response.getOutputStream();
			out.flush();

			int aRead = 0;
			byte b[] = new byte[1024];
			while ((aRead = in.read(b)) != -1 && in != null) {
				out.write(b, 0, aRead);
			}
			out.flush();
			in.close();
			out.close();
			System.out.println("下载成功");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}  catch (IOException e) {
			e.printStackTrace();
		}
	}
}
